from utils import get_app_book, get_date_str, get_info, save_wb
from datetime import datetime, timedelta
import shutil
import os


def copy_yesterday_report(file_name_yestoday=None, remove_exist=False):
    """
    复制昨天的报告。
    """
    if file_name_yestoday is None:
        file_name_yestoday = f"{get_date_str(-1)}.xlsx"
    file_name_today = f"{get_date_str()}.xlsx"
    # 检查前次报告文件是否存在
    if not os.path.exists(file_name_yestoday):
        # 使用红色输出
        print(f"\033[31m前次报告: {file_name_yestoday}不存在,脚本已停止\033[0m")
        return None

    # 检查今天的报告文件是否存在
    if os.path.exists(file_name_today) and remove_exist:
        print(f"\033[33m今天的报告: {file_name_today}已存在,已删除\033[0m")
        os.remove(file_name_today)
    elif os.path.exists(file_name_today):
        # 重命名文件后缀数字，直至找到一个不存在的文件名
        i = 1
        while os.path.exists(f"{file_name_today[:10]}_{i}.xlsx"):
            i += 1
        # 使用红色输出
        print(
            f"\033[33m今天的报告: {file_name_today}已存在,已重命名为{file_name_today[:10]}_{i}.xlsx\033[0m"
        )
        file_name_today = f"{file_name_today[:10]}_{i}.xlsx"

    shutil.copy(file_name_yestoday, file_name_today)
    print(f"复制成功: {file_name_yestoday} -> {file_name_today}")
    return file_name_today


def get_sheet_name_by_type(info_data, type_str):
    """
    根据类型获取工作表名
    """
    # 筛选字典数组info_data中type为type_str的字典
    return [key for key in info_data if info_data[key]["type"] == type_str]


def anlz_dr_sheet(sheet, info, wb):
    used_rows = sheet.UsedRange.Rows.Count
    used_cols = sheet.UsedRange.Columns.Count
    # .查找"{date}计划"
    td = datetime.now()
    tmr = td + timedelta(days=1)
    aftmr = td + timedelta(days=2)
    strs = [
        f"{td.month}月{td.day}日计划",
        f"{td.month}月{td.day}日实际",
        f"{tmr.month}月{tmr.day}日计划",
        f"{aftmr.month}月{aftmr.day}日计划",
    ]
    (py, px) = (None, None)
    for col_idx in range(1, used_cols + 1):
        for row_idx in range(1, used_rows + 1):
            if sheet.Cells(row_idx, col_idx).Value == strs[0]:
                (py, px) = (row_idx, col_idx)
                break

    if py is None or px is None:
        print("\033[31m表头坐标未找到\033[0m")
        return None
    else:
        print(f"表头坐标: {py, px}")

    # 验证后三个单元格
    if (
        sheet.Cells(py + 1, px).Value != strs[1]
        or sheet.Cells(py + 4, px).Value != strs[2]
        or sheet.Cells(py + 5, px).Value != strs[3]
    ):
        print(f"\033[31m表头验证失败, +1:{sheet.Cells(py + 1, px).Value}, +4:{sheet.Cells(py + 4, px).Value}, +5:{sheet.Cells(py + 5, px).Value}\033[0m")
        return None
    step = []
    for col_idx in range(px + 2, used_cols + 1):
        if sheet.Cells(py - 1, col_idx).Value is not None:
            step.append((col_idx, sheet.Cells(py - 1, col_idx).Value))

    print(f"工序: {step}, 工序数: {len(step)}")
    return {
        "ptd": (py, px),
        "atd": (py + 1, px),
        "ptm": (py + 4, px),
        "pat": (py + 5, px),
        "step": step,
    }


def main():
    file_name_today = copy_yesterday_report(remove_exist=True)
    if file_name_today is None:
        return

    # 打开工作簿
    wb, excel_app = get_app_book(file_name_today, True)
    if wb is None:
        return

    # 获取info
    date_cell, info_data = get_info(wb)
    # print(f"info工作表: {info_sheet}, info数据: {info_data}, 日期列: {date_col}")
    if date_cell is None or info_data is None:
        print("\033脚本已停止工作\033[0m")
        return
    print(f"info_data: {info_data}")

    # 获取所有dr工作表名
    dr_sheet_names = get_sheet_name_by_type(info_data, "dr")
    if dr_sheet_names is None:
        print("\033[31m未找到dr工作表\033[0m")
        return
    print(f"dr工作表名: {dr_sheet_names}")

    # 写入当前日期
    date_cell.Value = get_date_str().replace(".", "/")

    for name in dr_sheet_names:
        anlz_dr_sheet(wb.Sheets(name), info_data[name], wb)
        pass

    # 保存工作簿
    save_wb(wb, file_name_today, excel_app, True)


if __name__ == "__main__":
    main()
